package com.sanyou.controller;

import cn.hutool.core.util.ObjUtil;
import com.mchange.lang.DoubleUtils;
import com.sanyou.pojo.Factory;
import com.sanyou.pojo.vo.ProductNumVo;
import com.sanyou.pojo.vo.FactoryVo;
import com.sanyou.service.*;
import com.sanyou.utils.JSONResult;
import com.sanyou.utils.PagedResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.sanyou.controller.BasicController.PAGE_SIZE;

/**
 * User: asus
 * Date: 2021/5/26
 * Time: 1:43
 * Version:V1.0
 */
@Api(value = "厂家相关的接口",tags = {"厂家相关的Controller"})
@RestController
@CrossOrigin
@RequestMapping("/factory")
public class FactoryController {

    @Autowired
    private FactoryService factoryService;

    @Autowired
    private EquipmentService equipmentService;

    @Autowired
    private UserService userService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ProjectService projectService;
    /**
     * 新增冶炼厂
     * @param factory
     * @return
     */
    @ApiOperation(value = "新增冶炼厂", notes = "新增冶炼厂")
    @PostMapping("/addFactory")
    public JSONResult addFactory(@RequestBody Factory factory){
        if(factory == null || StringUtils.isBlank(factory.getFactoryName()))
            return JSONResult.errorMsg("厂家名不能为空!");

        Factory existFactory = factoryService.findByName(factory.getFactoryName(),factory.getParentId());
        if(existFactory == null){
            factoryService.addFactory(factory);
            return JSONResult.ok();
        }else{
            return JSONResult.errorMsg("厂家名已存在!");
        }

    }
    /**
     * 新增新增车间，必填字段：车间名，健康上限，亚健康上限，设备周期
     * @param factory
     * @return
     */
    @ApiOperation(value = "新增车间", notes = "新增车间")
    @PostMapping("/addSubFactory")
    public JSONResult addSubFactory(@RequestBody Factory factory, @RequestHeader(value="userId") String userId){
        if(factory == null || StringUtils.isBlank(factory.getFactoryName()))
            return JSONResult.errorMsg("车间名不能为空!");
        else if(factory.getEquipHealthLimit()<0)
            return JSONResult.errorMsg("设备健康上限不允许为负数!");
        else if(factory.getEquipSubHealthLimit()<factory.getEquipHealthLimit())
            return JSONResult.errorMsg("设备亚健康上限不允许小于设备健康上限!");
        else if(factory.getEquipCycle()<0)
            return JSONResult.errorMsg("设备周期不允许为负数!");

        Factory existFactory = factoryService.findByName(factory.getFactoryName(),factory.getParentId());
        if(existFactory == null){
            //添加车间
            factoryService.addFactory(factory);
            //添加用户权限,为添加车间的用户赋予数据权限
            if(StringUtils.isNotBlank(factory.getId())){
                userService.addAuthOfSubFactory(userId,factory.getId());
            }

            return JSONResult.ok();
        }else{
            return JSONResult.errorMsg("车间名已存在!");
        }

    }
    /**
     * 修改冶炼厂或者车间信息，根据前端返回的layer确定。 1：冶炼厂，2：车间
     * @param factory
     * @return
     */
    @ApiOperation(value = "修改冶炼厂或者车间信息", notes = "修改冶炼厂或者车间信息")
    @PostMapping("/updateFactoryInfo")
    public JSONResult updateFactoryInfo(@RequestBody Factory factory){
        if(factory == null || StringUtils.isBlank(factory.getId()))
            return JSONResult.errorMsg("厂家ID为空!");

        Factory findFactory = factoryService.findById(factory.getId());
        if(findFactory == null)
            return JSONResult.errorMsg("厂家不存在!");

        /* */
        if(factory.getLayer().intValue()==2){
            if(factory.getEquipCycle()==null)
                return JSONResult.errorMsg("设备周期不允许为空!");
            else if(factory.getEquipHealthLimit()==null)
                return JSONResult.errorMsg("设备健康上限不允许为空!");
            else if(factory.getEquipSubHealthLimit()==null)
                return JSONResult.errorMsg("设备亚健康上限不允许为空!");
            else if(factory.getEquipHealthLimit()<0)
                return JSONResult.errorMsg("设备健康上限不允许为负数!");
            else if(factory.getEquipSubHealthLimit()<factory.getEquipHealthLimit())
                return JSONResult.errorMsg("设备亚健康上限不允许小于设备健康上限!");
            else if(factory.getEquipCycle()<0)
                return JSONResult.errorMsg("设备周期不允许为负数!");
        } else {
            Factory existFactory = factoryService.findByName(factory.getFactoryName(),findFactory.getParentId());
            if(existFactory != null)
                return JSONResult.errorMsg("厂家名已存在!");
        }


        factoryService.updateFactoryInfo(factory);

        //同步更新车间下属的设备的健康及亚健康阈值和周期
        equipmentService.updateEquipmentBySubFactory(factory);
        return JSONResult.ok();

    }
    /**
     * 删除冶炼厂或者车间信息，删除车间需车间无项目，删除冶炼厂需现删除下属所有车间，所谓删除就是delete_mark置1
     * @param factory
     * @return
     */
    @ApiOperation(value = "删除冶炼厂或者车间信息", notes = "删除冶炼厂或者车间信息")
    @PostMapping("/deleteFactory")
    public JSONResult deleteFactory(@RequestBody Factory factory){
        if(factory == null || StringUtils.isBlank(factory.getId()))
            return JSONResult.errorMsg("厂家ID为空!");

        Factory findFactory = factoryService.findById(factory.getId());
        if(findFactory != null){
            //只能删除没有项目的车间
            if(findFactory.getLayer()==2 && projectService.listProject(findFactory.getId()).size() > 0){
                return JSONResult.errorMsg("车间下已存在项目，无法删除!");
            }
            //只能删除没有车间的工厂
            if(findFactory.getLayer()==1 && factoryService.getSubFactoryById(findFactory.getId()).size() > 0){
                return JSONResult.errorMsg("工厂下存在车间，无法删除!");
            }
            factoryService.updateFactoryInfo(factory);
            return JSONResult.ok();
        }else{
            return JSONResult.errorMsg("厂家不存在!");
        }
    }
    /**
     * 根据用户权限查看厂家列表，管理员可以看到所有厂家
     * @param query 本来用于车间名字模糊查询，但是后续未用到
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(name="query",value = "查询条件",required = false,
            dataType = "string", paramType = "query"),
            @ApiImplicitParam(name="page",value = "分页数",required = true,
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = false,
                    dataType = "int", paramType = "query")})
    @ApiOperation(value = "查看厂家列表", notes = "查看厂家列表，并分页返回")
    @GetMapping("/query")
    public JSONResult query(String query, Integer page, Integer pageSize){

        if(page == null)
            page = 1;

        if(pageSize == null)
            pageSize = PAGE_SIZE;

        PagedResult factoryList = factoryService.query(query, page, pageSize);

        return JSONResult.ok(factoryList);
    }
    /**
     * 根据用户权限查看厂家列表，管理员可以看到所有厂家
     * @param query 本来用于车间名字模糊查询，但是后续未用到
     * @return
     */
    @ApiOperation(value = "根据用户权限查看厂家列表", notes = "根据用户权限查看厂家列表，并分页返回")
    @GetMapping("/queryById")
    public JSONResult queryById(String query,String userId, Integer page, Integer pageSize){
        if(page == null)
            page = 1;
        if(pageSize == null)
            pageSize = PAGE_SIZE;
        PagedResult factoryList = factoryService.query(query, userId,page, pageSize);
        return JSONResult.ok(factoryList);
    }
    /**
     * 查询冶炼厂下属车间
     * @param parentId
     * @return
     */
    @ApiImplicitParam(name="parentId",value = "上级公司ID",required = true,
            dataType = "string", paramType = "query")
    @ApiOperation(value = "查询冶炼厂下属车间", notes = "查询冶炼厂下属车间")
    @GetMapping("/querySubFactory")
    public JSONResult querySubFactory(String parentId){

        if(StringUtils.isBlank(parentId))
            return JSONResult.errorMsg("上级厂家id为空!");

        List<Factory> list = factoryService.querySubFactory(parentId);
        return JSONResult.ok(list);
    }
    /**
     * 根据用户权限查询冶炼厂及其下属车间
     * @param parentId
     * @return
     */
    @ApiOperation(value = "根据用户权限查询冶炼厂及其下属车间", notes = "根据用户权限查询冶炼厂及其下属车间")
    @GetMapping("/querySubFactoryById")
    public JSONResult querySubFactoryById(String parentId,String userId){
        if(StringUtils.isBlank(parentId))
            return JSONResult.errorMsg("上级厂家id为空!");
        List<Factory> list = factoryService.querySubFactoryById(parentId,userId);
        return JSONResult.ok(list);
    }
    /**
     * 根据查询所有冶炼厂
     * @return
     */
    @ApiOperation(value = "查询所有厂家", notes = "查询所有厂家")
    @GetMapping("/getAll")
    public JSONResult getAll(){

        List<Factory> factoryList = factoryService.getAll();

        return JSONResult.ok(factoryList);
    }

    @ApiOperation(value = "获取厂家的树结构", notes = "获取厂家的树结构")
    @GetMapping("/getFactoryTree")
    public JSONResult getFactoryTree(){
        List<FactoryVo> factoryVoList = factoryService.getFactoryTree();
        return JSONResult.ok(factoryVoList);
    }
    /**
     * 根据用户权限查询冶炼厂
     * @param userId
     * @return
     */
    @ApiImplicitParam(name="userId",value = "用户id",required = true,
            dataType = "string", paramType = "query")
    @GetMapping("/getFactory")
    public JSONResult getFactory(String userId){
        if(StringUtils.isBlank(userId))
            return JSONResult.errorMsg("用户Id为空!");

        List<Factory> factoryList = factoryService.getFactory(userId);

        return JSONResult.ok(factoryList);
    }
    /**
     * 根据用户权限查询改冶炼厂下的车间
     * @param userId
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name="userId",value = "用户id",required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name="factoryId",value = "厂家id",required = true, dataType = "string", paramType = "query")
    })
    @GetMapping("/getSubFactory")
    public JSONResult getSubFactory(String userId,String factoryId){
        if(StringUtils.isBlank(userId))
            return JSONResult.errorMsg("用户Id为空!");

        if(StringUtils.isBlank(factoryId))
            return JSONResult.errorMsg("厂家Id为空!");

        List<Factory> subFactoryList = factoryService.getSubFactory(userId,factoryId);

        return JSONResult.ok(subFactoryList);
    }
    /**
     * 更新车间及设备地址
     * @param factory
     * @return
     */
    @ApiOperation(value = "更新车间及设备地址",notes = "更新车间及设备地址")
    @PostMapping("/updateAddress")
    public JSONResult updateAddress(@RequestBody Factory factory){
        if(factory == null || StringUtils.isBlank(factory.getId()))
            return JSONResult.errorMsg("工厂/车间ID不允许为空!");
        else if(factory.getEquipHealthLimit()<0)
            return JSONResult.errorMsg("设备健康上限不允许为负数!");
        else if(factory.getEquipSubHealthLimit()<factory.getEquipHealthLimit())
            return JSONResult.errorMsg("设备亚健康上限不允许小于设备健康上限!");
        else if(factory.getEquipCycle()<0)
            return JSONResult.errorMsg("设备周期不允许为负数!");

        factoryService.updateAddress(factory);

        return JSONResult.ok();
    }

    /**
     * 获取工厂名，车间名，经度，纬度，已编码阴极板数量和无编码阴极板数量
     */
    @GetMapping("/getFactoryAndProductCount")
    public JSONResult getFactoryAndProductCount(){

        List<ProductNumVo> productNumVos = productService.getFactoryAndProductCount();

        for (ProductNumVo productNumVo : productNumVos) {
            productNumVo.setUncodeNum(
                    productService.getUncodeNumBySubFactoryId(productNumVo.getSubFactoryId()));
        }

        return JSONResult.ok(productNumVos);
    }

}
